#include <Python.h>


int _sum(PyObject *nums) {
    int i;
    int size;
    long total;
    long num;

    size = (int) PyList_Size(nums);
    total = 0;

    for (i = 0; i < size; i++) {
        num = PyLong_AsLong(PyList_GetItem(nums, i));
        total += num;
    }
    return total;
}


static PyObject *sum(PyObject *self, PyObject *args) {
    PyObject *nums;

    if (!PyArg_ParseTuple(args, "O", &nums)) {
        PyErr_SetString(PyExc_RuntimeError, "error parsing arguments");
        return NULL;
    }

    if (!PyList_Check(nums)) {
        PyErr_SetString(PyExc_TypeError, "a list object is expected");
        return NULL;
    }

    return (PyObject *)Py_BuildValue("l", _sum(nums));
}


static PyMethodDef method[] = {
    {"sum", sum, METH_VARARGS, "\nsum([numbers]) -> int\n"},
    {NULL, NULL, 0, NULL},
};


static PyModuleDef module = {
    PyModuleDef_HEAD_INIT, "cext", NULL, -1, method
};


PyMODINIT_FUNC PyInit_cext(void) {
    return PyModule_Create(&module);
}
